# 11.3 I18nInterceptor
The I18nInterceptor
is a component provided for web applications to handle internationalization. Below is an example of how to use it in a Freemarker template:
# Configuration
First, configure I18nInterceptor
as a global interceptor.
public void configInterceptor(Interceptors me) {
me.add(new I18nInterceptor());
}
2
3
# Usage in Template
Then, in the JFinal template engine, you can use the _res
object to get internationalized data.
#(_res.get("msg"))
The above code configures I18nInterceptor
to intercept action requests and allows the Freemarker template files to use an object named _res
to get internationalized data. The specific workflow of I18nInterceptor
is as follows:
Tries to get the
locale
parameter from the request usingcontroller.getPara("_locale")
. If obtained, it saves it in a cookie.If
controller.getPara("_locale")
does not get a value, it tries to get thelocale
parameter fromcontroller.getCookie("_locale")
.If the above two steps still don't yield a
locale
parameter value, the value ofI18n.defaultLocale
is used as thelocale
.Using the
locale
value obtained in the previous steps,I18n.use(locale)
is called to get aRes
object. ThisRes
object is then passed to the view usingcontroller.setAttr("_res", res)
.If
I18nInterceptor.isSwitchView
is set totrue
, it will also change the rendered view, enabling the overall template file to switch. Details can be checked in the source code.
# Customization
The variable names "_locale" and "_res" used in I18nInterceptor
can be specified when creating the I18nInterceptor
object. If not specified, default values will be used. You can also extend I18nInterceptor
and override methods like getLocalPara
, getResName
, and getBaseName
to implement more personalized features.
# Advanced Usage
In some web systems, the page requires a lot of text to be internationalized, and the CSS and HTML may also vary greatly due to internationalization. For such use-cases, you can create multiple sets of internationalized views with the same name and categorize these views in subdirectories based on locale
. Finally, use the I18nInterceptor
to dynamically switch views based on the locale
. You just need to set I18nInterceptor.isSwitchView
to true
to achieve this, saving time and effort.